package com.juphoon.oauth.oauth;

import com.juphoon.oauth.core.authorize.CoreAuthorizeConfigManager;
import com.juphoon.oauth.core.config.Const;
import com.juphoon.oauth.core.properties.SecurityProperties;
import com.juphoon.oauth.core.vaildate.code.ValidateCodeSecurityConfig;
import com.juphoon.oauth.filter.CorsFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import org.springframework.web.cors.CorsUtils;

/**
 * @author rongbin.huang
 * oauth2 资源配置
 */
@Configuration
@EnableResourceServer
public class AppResourceAuthorizationConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    protected AuthenticationSuccessHandler appAuthenticationSuccessHandler;

    @Autowired
    protected AuthenticationFailureHandler appAuthenticationFailureHandler;

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private CoreAuthorizeConfigManager coreAuthorizeConfigManager;

    @Autowired
    private ValidateCodeSecurityConfig validateCodeSecurityConfig;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.addFilterBefore(new CorsFilter(), SecurityContextPersistenceFilter.class);

        http
                .apply(validateCodeSecurityConfig)
                .and()
                .formLogin()
                .usernameParameter(securityProperties.getOauth2().getUsernameParameter())
                .passwordParameter(securityProperties.getOauth2().getPasswordParameter())
                .loginProcessingUrl(securityProperties.getOauth2().getLoginUrl())
                .failureHandler(appAuthenticationFailureHandler)
                .successHandler(appAuthenticationSuccessHandler)
                .and()
                .csrf().disable();

        coreAuthorizeConfigManager.config(http.authorizeRequests());

    }

}
